import type { ChatRecordType } from '@/lib/interfaces'
import PubSub from 'pubsub-js'
import useAuthStore from '../stores/authStore'

export const ipcRenderer = () => {
  return window.ipcRenderer || null
}

// 登录窗口通信
const sendLoginWindow = (data: any) => {
  return ipcRenderer().invoke('sent-login-event', data)
}

// 主窗口通信
const sendMainWindow = (data: any) => {
  return ipcRenderer().invoke('sent-main-event', data)
}

// 主窗口通信
const sendMomentsWindow = (data: any) => {
  return ipcRenderer().invoke('sent-moment-event', data)
}

// 添加好友窗口通信
const sendFriendsWindow = (data: any) => {
  return ipcRenderer().invoke('sent-friends-event', data)
}

// 添加好友窗口通信
const piniaEvent = (data: any) => {
  return ipcRenderer().invoke('pinia-store-event', data)
}



// --------------------登录窗口事件-----------------------/
// 登陆成功
export const LoginSuccess = () => {
  const userInfo = useAuthStore().userInfo
  const token = useAuthStore().token
  sendLoginWindow({
    type: 'login-success',
    userId: userInfo.loginName,
    token: token
  })
}

// --------------------主窗口事件-----------------------/
// 登陆成功
export const loginOut = () => {
  sendMainWindow({
    type: 'login-out'
  })
}
// 检测当前用户是否同步过数据
export const queryUserIsLogin = (username: string) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'query-user-login',
        username: username
      })
    }
    resolve(hander())
  })
}

// 修改当前房间的未读数量
export const updateChatNoMessage = (roomId: string, reset: boolean) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'update-chat-no-message',
        roomId: roomId,
        reset: reset
      })
    }
    resolve(hander())
  })
}

// 向数据库中添加聊天室
export const insertChatRooms = (chatRoomList: any, userId: any) => {
  sendMainWindow({
    type: 'insert-chat-rooms',
    list: chatRoomList,
    userId: userId
  })
}

// 检测用户同步数据状态
export const updateUserIsLogin = (username: string) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'update-user-user',
        username: username
      })
    }
    resolve(hander())
  })
}

// 查询聊天房间
export const queryChatRooms = (username: string) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'query-chat-rooms',
        username: username
      })
    }
    resolve(hander())
  })
}

// 查询好友信息
export const queryFriendRelation = (username: string) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'query-friend-relation',
        username: username
      })
    }
    resolve(hander())
  })
}

// 查询好友信息
export const queryFriendRequests = (userId: string) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'query-friend-requests',
        userId: userId
      })
    }
    resolve(hander())
  })
}

// 向数据库中添加好友列表
export const insertFriendsRelationShip = (relationList: any) => {
  sendMainWindow({
    type: 'insert-friend-relation',
    relationList: relationList,
  })
}

// 向数据库中添加单个好友请求
export const insertFriendRequest = (request: any) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'insert-friend-request',
        request: request,
      })
    }
    resolve(hander())
  })
}

// 向数据库中添加好友请求列表
export const insertFriendsRequests = (requestList: any) => {
  sendMainWindow({
    type: 'insert-friend-requests',
    requestList: requestList,
  })
}

// 向数据库中添加聊天记录
export const insertChatRecords = (recordsList: Array<ChatRecordType>) => {
  sendMainWindow({
    type: 'insert-chat-recordList',
    list: recordsList,
  })
}


// 向数据库中添加聊天记录
export const insertChatRecord = (record: ChatRecordType) => {
  return new Promise((resolve, reject) => {
    const handler = async() => {
      return await sendMainWindow({
        type: 'insert-chat-record',
        list: record
      })
    }
    resolve(handler())
  })
}

// 向数据库中添加聊天室
export const sendSocketMessage = (messageObj: any) => {
  sendMainWindow({
    type: 'ev:send-chat-message',
    messageObj: messageObj,
  })
}

// 修改消息的状态
export const updateMessageStatus = (params: any) => {
  sendMainWindow({
    type: 'ev:update-chat-message',
    id: params.id,
    messageId: params.messageId,
    status: params.status
  })
}

// 修改消息的图片URl
export const updateMessageDataUrl = (params: any) => {
  sendMainWindow({
    type: 'ev:update-chat-message-img',
    id: params.id,
    img: params.img
  })
}


// 根据聊天ID查询聊天记录
export const getChatRecordsByRoomId = (roomId: string, start: Number, pos: Number) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'query-chat-rooms-records',
        roomId: roomId,
        start: start,
        pos: pos
      })
    }
    resolve(hander())
  })
}

// 根据聊天房间内最新的一条聊天记录（非时间消息）
export const getTheLatestMessage = (roomId: string) => {
  return new Promise((resolve, reject) => {
    const hander = async () => {
      return await sendMainWindow({
        type: 'query-chat-latest-records',
        roomId: roomId
      })
    }
    resolve(hander())
  })
}

// 调用截屏程序
export const getPrintScr = () => {
  return sendMainWindow({
    type: 'ev:print-scr',
  })
}

// 打开朋友圈
export const showMomentsWin = (data: any) => {
  sendMainWindow({
    type: 'wechat-moments'
  })
}

// 关闭朋友圈
export const closeMomentsWin = () => {
  sendMomentsWindow({
    type: 'close:moment'
  })
}

// 打开好友请求窗口
export const showFriendsRequestWin = (data: any) => {
  sendMainWindow({
    type: 'friends-request',
    ...data
  })
}

// 关闭好友请求窗口
export const closeFriendsRequestWin = (data: any) => {
  sendFriendsWindow({
    type: 'closed'
  })
}

// 打开通话窗口
export const showVoiceCallWin = (data: any) => {
  sendMainWindow({
    type: 'ev:voice-page',
    roomId: data.roomInfo.id,
    roomName: data.roomInfo.roomName,
    avatar: data.roomInfo.avatar,
    callType: data.callType
  })
}

// 打开文件系统
export const openFileDialogHandler = () => {
  sendMainWindow({
    type: 'ev:open-file-dialog'
  })
}

// 打开聊天记录窗口
export const showChatRecordWin = (params: any) => {
  sendMainWindow({
    type: 'ev:records-page',
    roomName: params.roomName,
    roomId: params.id
  })
}

// 关闭聊天记录窗口
export const closeChatRecordWin = () => {
  return ipcRenderer().invoke('sent-record-event', {
    type: 'ev:close-records',
  })
}

// 关闭通话窗口
export const closeVideoCallWin = () => {
  return sendMainWindow({
    type: 'ev:close-call',
  })
}

// 获取数据
export const getElectronStoreData = (key: string) => {
  return piniaEvent({
    type: 'pinia-get-store',
    key: key
  })
}

// 设置数据
export const setElectronStoreData = (key: string, dataStr: string) => {
  console.log('setElectronStoreData', key)
  console.log('setElectronStoreData', dataStr)
  return piniaEvent({
    type: 'pinia-set-store',
    key: key,
    dataStr: dataStr
  })
}

// 修改数据
export const changeElectronStoreData = (storeName: string, dataStr: string) => {
  return piniaEvent({
    type: 'pinia-change-store',
    storeName: storeName,
    data: dataStr
  })
}



// 获取设备窗口信息（暂未使用到）
// export const getWindowsInfo = () => {
//   return ipcRenderer().invoke('sent-event', {
//     type: 'ev:send-desktop-capturer_source',
//   })
// }

// // 显示截屏程序（暂未使用到）
// export const showScrWinodw = () => {
//   return ipcRenderer().invoke('sent-event', {
//     type: 'ev:show-screen',
//   })
// }

// // 隐藏截屏程序（暂未使用到）
// export const hideScrWinodw = () => {
//   return ipcRenderer().invoke('sent-event', {
//     type: 'ev:hide-screen',
//   })
// }